// 圈子类型枚举
enum CircleType {

  city('city', '城市圈'),
  country('country', '国家圈'),
  global('global', '全球圈');
  
  const CircleType(this.value, this.displayName);
  final String value;
  final String displayName;
}
// 圈子模型
class Circle {
  final int id;
  final String name;
  final CircleType type;
  final String? countryCode;
  final String? cityCode;
  final String description;
  final String? coverImage;
  final int memberCount;
  final int postCount;
  final bool isActive;
  final DateTime createdAt;
  final DateTime updatedAt;

  Circle({
    required this.id,
    required this.name,
    required this.type,
    this.countryCode,
    this.cityCode,
    required this.description,
    this.coverImage,
    this.memberCount = 0,
    this.postCount = 0,
    this.isActive = true,
    required this.createdAt,
    required this.updatedAt,
  });

  factory Circle.fromJson(Map<String, dynamic> json) {
    return Circle(
      id: json['id'],
      name: json['name'],
      type: CircleType.values.firstWhere(
        (e) => e.value == json['type'],
        orElse: () => CircleType.global,
      ),
      countryCode: json['country_code'],
      cityCode: json['city_code'],
      description: json['description'] ?? '',
      coverImage: json['cover_image'],
      memberCount: json['member_count'] ?? 0,
      postCount: json['post_count'] ?? 0,
      isActive: json['is_active'] ?? true,
      createdAt: DateTime.parse(json['created_at']),
      updatedAt: DateTime.parse(json['updated_at']),
    );
  }

  Map<String, dynamic> toJson() {
    return {
      'id': id,
      'name': name,
      'type': type.value,
      'country_code': countryCode,
      'city_code': cityCode,
      'description': description,
      'cover_image': coverImage,
      'member_count': memberCount,
      'post_count': postCount,
      'is_active': isActive,
      'created_at': createdAt.toIso8601String(),
      'updated_at': updatedAt.toIso8601String(),
    };
  }
}
// 帖子标签模型
class PostTag {
  final String id;
  final String name;
  final CircleType type;
  final String? color;
  final bool isDefault;

  PostTag({
    required this.id,
    required this.name,
    required this.type,
    this.color,
    this.isDefault = false,
  });

  factory PostTag.fromJson(Map<String, dynamic> json) {
    return PostTag(
      id: json['id'].toString(),
      name: json['name'],
      type: CircleType.values.firstWhere(
        (e) => e.value == json['type'],
        orElse: () => CircleType.global,
      ),
      color: json['color'],
      isDefault: json['isDefault'] ?? false,
    );
  }

  Map<String, dynamic> toJson() {
    return {
      'id': id,
      'name': name,
      'type': type.value,
      'color': color,
      'isDefault': isDefault,
    };
  }

  @override
  bool operator ==(Object other) {
    if (identical(this, other)) return true;
    return other is PostTag && other.id == id;
  }

  @override
  int get hashCode => id.hashCode;
}

// 圈子帖子模型
class CirclePost {
  final String id;
  final String userId;
  final String userName;
  final String userAvatar;
  final String content;
  final List<String> images;
  final List<String> videos;
  final List<PostTag> tags;
  final DateTime createdAt;
  final int likeCount;
  final int commentCount;
  final int shareCount;
  final bool isLiked;
  final bool isBookmarked;
   // 新增圈子信息字段
  final int? circleId;
  final String? circleName;
  final CircleType? circleType;
  final Circle? circle; // 完整的圈子对象（可选）

    // 新增：位置字段
  final double? locationLatitude;
  final double? locationLongitude;
  final String? locationAddress;

  CirclePost({
    required this.id,
    required this.userId,
    required this.userName,
    required this.userAvatar,
    required this.content,
    required this.images,
    this.videos = const [],
    required this.tags,
    required this.createdAt,
    this.likeCount = 0,
    this.commentCount = 0,
    this.shareCount = 0,
    this.isLiked = false,
    this.isBookmarked = false,
    // 新增圈子信息参数
    this.circleId,
    this.circleName,
    this.circleType,
    this.circle,

        // 新增：位置字段
    this.locationLatitude,
    this.locationLongitude,
    this.locationAddress,
  });

  factory CirclePost.fromJson(Map<String, dynamic> json) {

    double? _parseDouble(dynamic v) {
      if (v == null) return null;
      if (v is num) return v.toDouble();
      if (v is String) return double.tryParse(v);
      return null;
    }

    return CirclePost(
      id: json['id'],
      userId: json['userId'],
      userName: json['userName'],
      userAvatar: json['userAvatar'] ?? '',
      content: json['content'] ?? '',
      images: List<String>.from(json['images'] ?? []),
       // 新增：视频列表解析
      videos: List<String>.from(json['videos'] ?? []),
      tags: (json['tags'] as List<dynamic>? ?? [])
          .map((tag) => PostTag.fromJson(tag))
          .toList(),
      createdAt: DateTime.parse(json['createdAt']),
      likeCount: json['like_count'] ?? 0,
      commentCount: json['commentCount'] ?? 0,
      shareCount: json['share_count'] ?? 0,
      isLiked: json['is_liked'] ?? false,
      isBookmarked: json['is_collected'] ?? false,
       // 解析圈子信息
      circleId: json['circle_id'],
      circleName: json['circle_name'],
      circleType: json['circle_type'] != null
          ? CircleType.values.firstWhere(
              (e) => e.value == json['circle_type'],
              orElse: () => CircleType.global,
            )
          : null,
      circle: json['circle'] != null
          ? Circle.fromJson(json['circle'])
          : null,
       // 新增：位置字段解析
      locationLatitude: _parseDouble(json['location_latitude']),
      locationLongitude: _parseDouble(json['location_longitude']),
      locationAddress: json['location_address'],
    );
  }

  Map<String, dynamic> toJson() {
    return {
      'id': id,
      'userId': userId,
      'userName': userName,
      'userAvatar': userAvatar,
      'content': content,
      'images': images,
      // 新增：视频列表序列化
      'videos': videos,
      'tags': tags.map((tag) => tag.toJson()).toList(),
      'createdAt': createdAt.toIso8601String(),
      'likeCount': likeCount,
      'commentCount': commentCount,
      'shareCount': shareCount,
      'isLiked': isLiked,
      'isBookmarked': isBookmarked,
       // 序列化圈子信息
      'circle_id': circleId,
      'circle_name': circleName,
      'circle_type': circleType?.value,
      'circle': circle?.toJson(),
      // 新增：位置字段序列化
      'location_latitude': locationLatitude,
      'location_longitude': locationLongitude,
      'location_address': locationAddress,
    };
  }
  // 便利方法：获取圈子显示名称
  String get circleDisplayName {
    if (circleName != null) return circleName!;
    if (circleType != null) return circleType!.displayName;
    return '未知圈子';
  }

  // 便利方法：检查是否属于指定圈子类型
  bool belongsToCircleType(CircleType type) {
    // 优先使用 circleType 字段
    if (circleType != null) {
      return circleType == type;
    }
    
    // 如果没有 circleType，通过标签判断
    return tags.any((tag) => tag.type == type);
  }
  String get timeAgo {
    final now = DateTime.now();
    final difference = now.difference(createdAt);
    
    if (difference.inMinutes < 1) {
      return '刚刚';
    } else if (difference.inHours < 1) {
      return '${difference.inMinutes}分钟前';
    } else if (difference.inDays < 1) {
      return '${difference.inHours}小时前';
    } else if (difference.inDays < 7) {
      return '${difference.inDays}天前';
    } else {
      return '${createdAt.month}月${createdAt.day}日';
    }
  }

  // copyWith 方法：创建具有部分更新字段的新实例
  CirclePost copyWith({
    String? id,
    String? userId,
    String? userName,
    String? userAvatar,
    String? content,
    List<String>? images,
    List<String>? videos,
    List<PostTag>? tags,
    DateTime? createdAt,
    int? likeCount,
    int? commentCount,
    int? shareCount,
    bool? isLiked,
    bool? isBookmarked,
    int? circleId,
    String? circleName,
    CircleType? circleType,
    Circle? circle,
    double? locationLatitude,
    double? locationLongitude,
    String? locationAddress,
  }) {
    return CirclePost(
      id: id ?? this.id,
      userId: userId ?? this.userId,
      userName: userName ?? this.userName,
      userAvatar: userAvatar ?? this.userAvatar,
      content: content ?? this.content,
      images: images ?? this.images,
      videos: videos ?? this.videos,
      tags: tags ?? this.tags,
      createdAt: createdAt ?? this.createdAt,
      likeCount: likeCount ?? this.likeCount,
      commentCount: commentCount ?? this.commentCount,
      shareCount: shareCount ?? this.shareCount,
      isLiked: isLiked ?? this.isLiked,
      isBookmarked: isBookmarked ?? this.isBookmarked,
      circleId: circleId ?? this.circleId,
      circleName: circleName ?? this.circleName,
      circleType: circleType ?? this.circleType,
      circle: circle ?? this.circle,
      locationLatitude: locationLatitude ?? this.locationLatitude,
      locationLongitude: locationLongitude ?? this.locationLongitude,
      locationAddress: locationAddress ?? this.locationAddress,
    );
  }
}

// 通知类型枚举
enum NotificationType {
  like('like', '点赞'),
  comment('comment', '评论'),
  reply('reply', '回复'),
  mention('mention', '提及'),
  follow('follow', '关注'),
  system('system', '系统通知');

  const NotificationType(this.value, this.displayName);
  final String value;
  final String displayName;
}

// 通知模型
class PostNotification {
  final String id;
  final String postId;
  final String fromUserId;
  final String fromUserName;
  final String fromUserAvatar;
  final NotificationType type;
  final String content;
  final DateTime createdAt;
  final bool isRead;
  final String? targetContent; // 被点赞/评论的内容片段

  PostNotification({
    required this.id,
    required this.postId,
    required this.fromUserId,
    required this.fromUserName,
    required this.fromUserAvatar,
    required this.type,
    required this.content,
    required this.createdAt,
    this.isRead = false,
    this.targetContent,
  });

  factory PostNotification.fromJson(Map<String, dynamic> json) {
    return PostNotification(
      id: json['id'],
      postId: json['postId'],
      fromUserId: json['fromUserId'],
      fromUserName: json['fromUserName'],
      fromUserAvatar: json['fromUserAvatar'] ?? '',
      type: NotificationType.values.firstWhere(
        (e) => e.value == json['type'],
        orElse: () => NotificationType.system,
      ),
      content: json['content'],
      createdAt: DateTime.parse(json['createdAt']),
      isRead: json['isRead'] ?? false,
      targetContent: json['targetContent'],
    );
  }

  Map<String, dynamic> toJson() {
    return {
      'id': id,
      'postId': postId,
      'fromUserId': fromUserId,
      'fromUserName': fromUserName,
      'fromUserAvatar': fromUserAvatar,
      'type': type.value,
      'content': content,
      'createdAt': createdAt.toIso8601String(),
      'isRead': isRead,
      'targetContent': targetContent,
    };
  }

  String get timeAgo {
    final now = DateTime.now();
    final difference = now.difference(createdAt);
    
    if (difference.inMinutes < 1) {
      return '刚刚';
    } else if (difference.inHours < 1) {
      return '${difference.inMinutes}分钟前';
    } else if (difference.inDays < 1) {
      return '${difference.inHours}小时前';
    } else if (difference.inDays < 7) {
      return '${difference.inDays}天前';
    } else {
      return '${createdAt.month}月${createdAt.day}日';
    }
  }

  String get displayText {
    switch (type) {
      case NotificationType.like:
        return '$fromUserName 赞了你的帖子';
      case NotificationType.comment:
        return '$fromUserName 评论了你的帖子';
      case NotificationType.reply:
        return '$fromUserName 回复了你';
      case NotificationType.mention:
        return '$fromUserName 在帖子中提到了你';
      case NotificationType.follow:
        return '$fromUserName 关注了你';
      case NotificationType.system:
        return content;
    }
  }
}